package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.controlserver.ControlServer;
import com.ruoyi.system.controlserver.SmartInfo;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 服务器ip列表
 *
 * @author chenjy
 */
@RestController
@RequestMapping("/system/serverInfo")
public class ServerInfoController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(ServerInfoController.class);
    //    private final String path = "/root/serverInfo";
    private final String path = "d://root//serverInfo//serverInfo.txt";
    @Autowired
    private ControlServer controlServer;

    /**
     * 获取所有服务器ip
     */
    @GetMapping("/list")
    public AjaxResult list() {
        List<ServerInfo> list = new ArrayList<>();
        JSONObject jsonObject = readFile();
        if (jsonObject == null || jsonObject.isEmpty()) {
            final String hostIp = IpUtils.getHostIp();
            int port = 9900;
            final ServerInfo serverInfo = new ServerInfo();
            serverInfo.setIp(hostIp);
            serverInfo.setPort(port);
            list.add(serverInfo);
            return success(list);
        }
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            ServerInfo serverInfo = new ServerInfo();
            String[] array = key.split(":");
            serverInfo.setIp(array[0]);
            serverInfo.setPort(Integer.parseInt(array[1]));
            serverInfo.setPublish((Boolean) value);
            list.add(serverInfo);
        }
        return success(list);
    }

    /**
     * 添加服务器ip
     */
    @PostMapping("/addServerInfo")
    public AjaxResult addServerInfo(@Validated @RequestBody ServerInfo info) {
        JSONObject jsonObject = readFile();
        jsonObject.put(info.getIp().concat(":").concat(String.valueOf(info.getPort())), false);
        try {
            FileUtils.writeStringToFile(Paths.get(path).toFile(), jsonObject.toJSONString(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("服务器数据保存失败", e);
            throw new ServiceException("数据保存失败：" + e.getMessage());
        }
        return toAjax(true);
    }


    /**
     * 将服务器ip推送至智慧屏
     */
    @PostMapping("/publish")
    public AjaxResult publish(@Validated @RequestBody ServerInfo info) {
        String instruction = "serverInfo:".concat(info.getIp().concat(":").concat(String.valueOf(info.getPort())));
        Map<String, SmartInfo> channelMap = controlServer.getChannelMap();
        for (SmartInfo smartInfo : channelMap.values()) {
            smartInfo.getChannel().writeAndFlush(instruction);
        }
        JSONObject jsonObject = readFile();
        jsonObject.put(info.getIp().concat(":").concat(String.valueOf(info.getPort())), true);
        try {
            FileUtils.writeStringToFile(Paths.get(path).toFile(), jsonObject.toJSONString(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("服务器数据保存失败", e);
            throw new ServiceException("数据保存失败：" + e.getMessage());
        }
        return toAjax(true);
    }

    private JSONObject readFile() {
        String content;
        try {
            content = FileUtils.readFileToString(Paths.get(path).toFile(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("读取服务器ip列表失败", e);
            return new JSONObject();
        }
        try {
            if (StringUtils.isBlank(content)) {
                return new JSONObject();
            }
            return JSONObject.parseObject(content);
        } catch (Exception e) {
            log.error("解析服务器ip列表失败", e);
            return new JSONObject();
        }
    }

    static class ServerInfo {
        private String ip;
        private int port;
        private boolean publish;

        public String getIp() {
            return ip;
        }

        public void setIp(String ip) {
            this.ip = ip;
        }

        public int getPort() {
            return port;
        }

        public void setPort(int port) {
            this.port = port;
        }

        public boolean getPublish() {
            return publish;
        }

        public void setPublish(boolean publish) {
            this.publish = publish;
        }
    }


}
